<?php
// 应用公共文件
function setPassword($password, $encode = ""): array
{
    if (empty($encode)) $encode = \think\helper\Str::random(32);
    $password = password_hash($password . $encode, PASSWORD_DEFAULT);
    return ['password' => $password, 'encode' => $encode];
}

function checkPassword($password, $encode, $password_hash): bool
{
    return password_verify($password . $encode, $password_hash);
}

function getAuthorization()
{
    $author = request()->header("authorization");
    if (empty($author)) throw new \Exception("请登录", 7004);
    return json_decode($author, true);
}

function realDomain(): string
{
    $url = request()->domain();
    if (request()->ip() == "127.0.0.1") $url = "https://panda.verjs.cn";
    return $url;
}

function readExcel($files, $change = [])
{
    $objReader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader("Xlsx");
    $objPHPExcel = $objReader->load($files);
    $sheet = $objPHPExcel->getSheet(0);   //excel中的第一张sheet
    $data = $sheet->toArray();
    $key = array_shift($data);
    $result = [];
    if (!empty($data)) {
        $count = 0;
        foreach ($data as $k => $value) {
            foreach ($value as $a => $v) {
                $ks = $key[$a];
                if (!empty($change) && !empty($change[$ks])) {
                    $ks = preg_match('/\//', $change[$ks]) ? explode("/", $change[$ks]) : $change[$ks];
                    if (is_array($ks)) {
                        $result[$count][$ks[0]][$ks[1]] = $v;
                    } else {
                        $result[$count][$ks] = $v;
                    }
                } elseif (empty($change)) {
                    $result[$count][$ks] = $v;
                }
            }
            $count++;
        }
    }
    return $result;
}

function sendSms($tpl,$mobile,$message): bool
{
    $sms = new \zt_sms\ZtSms();
    $items = $sms->init()->setBiz("/v2/sendSmsTp")->setData([
        "signature" => "【成都富海天下】",
        "tpId" => $tpl,
        "records" => [
            [
                "mobile" => $mobile,
                "tpContent" => $message
            ]
        ]
    ])->send();
    return !empty($items) && strtolower($items['msg']) == "success";
}
